//
//  NSObject+PrintIvars.swift
//  53.表情键盘新工程
//
//  Created by gzxzmac on 16/4/2.
//  Copyright © 2016年 gzxzmac. All rights reserved.
//

import Foundation

/// 返回值对应表
let ivarTypeDict = [":": "SEL", "#": "Class", "@": "id", "*": "char *", "v": "Void", "B": "Bool", "d": "Double", "f": "Float", "Q": "Long", "L": "Long", "S": "Short", "I": "Int", "C": "Char", "q": "Long", "c": "Char", "i": "Int", "s": "Short", "l": "Long"]

extension NSObject {
    class func printIvars() {
        // 使用运行时查看隐藏的属性
        /*
        运行时开头关键字: 1.objc 2.class 3.method 4.object 5.protocol 6.ivar
        */
        /// 拷贝类的成员变量
        /// outCount: UnsafeMutablePointer<UInt32>: 成员变量的数量
        /// 返回值: UnsafeMutablePointer<Ivar>: 是一个地址,数组的地址, 数组的名字,是数组第一个元素的地址
        var count: UInt32 = 0
        let ivars = class_copyIvarList(self, &count)
        print("类的成员变量---\(self)开始")
        for i in 0..<count {
            /// 取出数组中的元素
            let ivar = ivars[Int(i)]
            
            let cName = ivar_getName(ivar)   // char类型的地址
            let name = String(CString: cName, encoding: NSUTF8StringEncoding)!
            
            let cType = ivar_getTypeEncoding(ivar)
            var type = String(CString: cType, encoding: NSUTF8StringEncoding)!
            
            // 去字典里面查找新的类型图片
            if let newType = ivarTypeDict[type] {
                type = newType
            }
            print("name: \(name), type: \(type)")
        }
        print("类的成员变量---\(self)结束")
        
        free(ivars)
    }
}